package com.woniuxy.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ORDER_LIST_CACHE_KEY_PREFIX = "order:list:";
    private static final String ORDER_DETAIL_CACHE_KEY_PREFIX = "order:detail:";
    private static final int CACHE_EXPIRE_MINUTES = 5;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 获取订单列表（带缓存）
    @Override
    public List<ShopOrder> getMyOrderList(Integer userId) {
        String cacheKey = ORDER_LIST_CACHE_KEY_PREFIX + userId;

        String cachedJson = redisTemplate.opsForValue().get(cacheKey);
        if (cachedJson != null && !cachedJson.isEmpty()) {
            try {
                return objectMapper.readValue(cachedJson, objectMapper.getTypeFactory().constructCollectionType(List.class, ShopOrder.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List<ShopOrder> orders = orderMapper.selectByUserId(userId);
        if (orders != null && !orders.isEmpty()) {
            try {
                String json = objectMapper.writeValueAsString(orders);
                redisTemplate.opsForValue().set(cacheKey, json, CACHE_EXPIRE_MINUTES, TimeUnit.MINUTES);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return orders;
    }

    // 根据订单编号获取订单详情（带缓存）
    @Override
    public ShopOrder getOrderById(String orderId) {
        String cacheKey = ORDER_DETAIL_CACHE_KEY_PREFIX + orderId;

        String cachedJson = redisTemplate.opsForValue().get(cacheKey);
        if (cachedJson != null && !cachedJson.isEmpty()) {
            try {
                return objectMapper.readValue(cachedJson, ShopOrder.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ShopOrder order = orderMapper.selectById(orderId);
        if (order != null) {
            try {
                String json = objectMapper.writeValueAsString(order);
                redisTemplate.opsForValue().set(cacheKey, json, CACHE_EXPIRE_MINUTES, TimeUnit.MINUTES);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return order;
    }

    // 删除订单（同时删除缓存）
    @Override
    public boolean deleteOrder(String orderId) {
        ShopOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        Integer userId = order.getUserId();
        orderMapper.delete(orderId);

        // 删除缓存
        String listCacheKey = ORDER_LIST_CACHE_KEY_PREFIX + userId;
        String detailCacheKey = ORDER_DETAIL_CACHE_KEY_PREFIX + orderId;

        redisTemplate.delete(listCacheKey);
        redisTemplate.delete(detailCacheKey);

        return true;
    }
}
